<template>
  <div class="dictionary-maintenance">
    <div class="container">
      <div class="action-filter-bar card mb-4">
        <div class="action-filter-row">
          <div class="action-buttons">
            <el-button class="btn btn-compact" @click="goBack">
              <ArrowLeftIcon :size="14" />
              返回
            </el-button>
            <el-button class="btn btn-compact btn-primary" @click="showAddTagDialog = true">
              <PlusIcon :size="14" />
              新增
            </el-button>
            <el-button class="btn btn-compact" @click="handleImport">
              <ImportIcon :size="14" />
              导入
            </el-button>
            <el-button class="btn btn-compact" @click="handleExport">
              <ExportIcon :size="14" />
              导出
            </el-button>
          </div>
          <div class="filter-groups">
            <div class="filter-group">
              <label>维度：</label>
              <select v-model="selectedDimension" class="select">
                <option
                  v-for="(label, key) in dimensionOptions"
                  :key="key"
                  :value="DICTIONARY_TYPES[key]"
                >
                  {{ label }}
                </option>
              </select>
            </div>
            <div class="filter-group">
              <label>搜索：</label>
              <input type="text" placeholder="搜索标签" class="input" v-model="searchQuery" />
              <el-button class="btn btn-compact" @click="searchData">
                <SearchIcon :size="14" />
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <div class="dictionary-table card">
        <div v-if="loading" class="loading-placeholder">正在加载数据...</div>
        <div v-else-if="filteredItems.length === 0" class="empty-placeholder">暂无数据</div>
        <table v-else class="table">
          <thead>
            <tr>
              <th>序号</th>
              <th>可见名</th>
              <th>系统名</th>
              <th>使用计数</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in filteredItems" :key="item.id">
              <td>{{ index + 1 }}</td>
              <td>{{ item.name }}</td>
              <td>{{ item.id }}</td>
              <td>{{ item.count }}</td>
              <td>
                <span
                  class="badge"
                  :class="item.status === 'active' ? 'badge-success' : 'badge-pending'"
                >
                  {{ item.status === 'active' ? '启用' : '停用' }}
                </span>
              </td>
              <td>
                <div class="action-buttons">
                  <button class="btn" @click="openEditDialog(item)">重命名</button>
                  <button class="btn" @click="toggleStatus(item)">
                    {{ item.status === 'active' ? '停用' : '启用' }}
                  </button>
                  <button class="btn btn-error" @click="openDeleteDialog(item)">删除</button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 新增标签弹窗 -->
    <div v-if="showAddTagDialog" class="dialog-overlay" @click="handleOverlayClick">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>新增标签</h3>
          <button class="close-btn" @click="closeAddTagDialog">
            <XIcon :size="16" />
          </button>
        </div>
        <div class="dialog-body">
          <div class="form-group">
            <label>可见名：</label>
            <input
              type="text"
              v-model="newTagName"
              placeholder="请输入可见名"
              class="input"
              @keyup.enter="handleAddTag"
            />
          </div>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-secondary" @click="closeAddTagDialog">取消</button>
          <button class="btn btn-primary" @click="handleAddTag" :disabled="!newTagName.trim()">
            确定
          </button>
        </div>
      </div>
    </div>

    <!-- 编辑标签弹窗 -->
    <div v-if="showEditDialog" class="dialog-overlay" @click="closeEditDialog">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>编辑标签</h3>
          <button class="close-btn" @click="closeEditDialog">
            <XIcon :size="16" />
          </button>
        </div>
        <div class="dialog-body">
          <div class="form-group">
            <label>可见名：</label>
            <input
              type="text"
              v-model="editTagName"
              placeholder="请输入可见名"
              class="input"
              @keyup.enter="handleEditTag"
            />
          </div>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-secondary" @click="closeEditDialog">取消</button>
          <button class="btn btn-primary" @click="handleEditTag" :disabled="!editTagName.trim()">
            确定
          </button>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteDialog" class="dialog-overlay" @click="closeDeleteDialog">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>删除确认</h3>
          <button class="close-btn" @click="closeDeleteDialog">
            <XIcon :size="16" />
          </button>
        </div>
        <div class="dialog-body">
          <p>确定要删除标签 "{{ deletingItem?.name }}" 吗？</p>
          <p class="warning-text">删除后无法恢复，请谨慎操作！</p>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-secondary" @click="closeDeleteDialog">取消</button>
          <button class="btn btn-error" @click="handleDeleteTag">确定删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  getAllDictionaries,
  getDictionaryByType,
  searchDictionaryItems,
  createDictionaryItem,
  updateDictionaryItem,
  deleteDictionaryItem,
  importDictionaryData,
  exportDictionaryData,
  getDictionaryTypes,
  DICTIONARY_TYPES,
  ITEM_STATUS,
} from '../api/dictionaryApi'
import {
  PlusIcon,
  ArrowLeftIcon,
  SearchIcon,
  ImportIcon,
  ExportIcon,
  XIcon,
} from '../components/icons'

export default {
  name: 'DictionaryMaintenance',
  components: {
    PlusIcon,
    ArrowLeftIcon,
    SearchIcon,
    ImportIcon,
    ExportIcon,
    XIcon,
  },
  setup() {
    const router = useRouter()
    const selectedDimension = ref(DICTIONARY_TYPES.CLOTHING_TYPES)
    const searchQuery = ref('')
    const dictionaries = ref({})
    const loading = ref(false)
    const showAddTagDialog = ref(false)
    const newTagName = ref('')
    const showEditDialog = ref(false)
    const editingItem = ref(null)
    const editTagName = ref('')
    const showDeleteDialog = ref(false)
    const deletingItem = ref(null)

    // 维度选项配置 - 动态获取
    const dimensionOptions = ref({})
    const dictionaryTypes = ref([])

    // 加载字典类型
    const loadDictionaryTypes = async () => {
      try {
        const response = await getDictionaryTypes()
        if (response && response.types) {
          dictionaryTypes.value = response.types
          // 构建维度选项映射
          const options = {}
          response.types.forEach(type => {
            const key = Object.keys(DICTIONARY_TYPES).find(k => DICTIONARY_TYPES[k] === type.code)
            if (key) {
              options[key] = type.name
            }
          })
          dimensionOptions.value = options
        }
      } catch (error) {
        console.error('加载字典类型失败:', error)
        // 如果API调用失败，使用默认配置作为fallback
        dimensionOptions.value = {
          CLOTHING_TYPES: '服装类型',
          COLORS: '颜色',
          PATTERNS: '花色图案',
          MATERIALS: '材质特征',
          SLEEVE_TYPES: '袖型',
          COLLAR_TYPES: '领型',
        }
      }
    }

    // 加载数据
    const loadData = async () => {
      loading.value = true
      try {
        const data = await getAllDictionaries()
        dictionaries.value = data
      } catch (error) {
        console.error('加载数据失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 搜索数据
    const searchData = async () => {
      console.log(1111)

      if (!searchQuery.value.trim()) {
        await loadData()
        return
      }

      loading.value = true
      try {
        const result = await searchDictionaryItems(
          selectedDimension.value,
          searchQuery.value.trim(),
          {
            page: 1,
            pageSize: 100,
          }
        )
        // 将搜索结果转换为与 getAllDictionaries 相同的格式
        dictionaries.value = {
          ...dictionaries.value,
          [selectedDimension.value]: result.list || [],
        }
      } catch (error) {
        console.error('搜索数据失败:', error)
      } finally {
        loading.value = false
      }
    }

    const filteredItems = computed(() => {
      const items = dictionaries.value[selectedDimension.value] || []

      if (!searchQuery.value) return items

      return items.filter(
        item =>
          item.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
          item.id.toLowerCase().includes(searchQuery.value.toLowerCase())
      )
    })

    const goBack = () => {
      router.go(-1)
    }

    // 导入功能
    const handleImport = () => {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = '.txt,.xlsx,.xls,.csv'
      input.onchange = async event => {
        const file = event.target.files[0]
        if (file) {
          try {
            await importDictionaryData(selectedDimension.value, file)
            await loadData() // 重新加载数据
            window.$toast?.showSuccess('导入成功')
          } catch (error) {
            console.error('导入失败:', error)
            window.$toast?.showError('导入失败', error.message)
          }
        }
      }
      input.click()
    }

    // 导出功能
    const handleExport = async () => {
      try {
        await exportDictionaryData(selectedDimension.value, 'text')
        window.$toast?.showSuccess('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        window.$toast?.showError('导出失败', error.message)
      }
    }

    // 新增标签相关方法
    const closeAddTagDialog = () => {
      showAddTagDialog.value = false
      newTagName.value = ''
    }

    const handleOverlayClick = () => {
      closeAddTagDialog()
    }

    const handleAddTag = async () => {
      if (newTagName.value.trim()) {
        try {
          await createDictionaryItem(selectedDimension.value, {
            name: newTagName.value.trim(),
            status: ITEM_STATUS.ACTIVE,
          })
          await loadData() // 重新加载数据
          closeAddTagDialog()
          window.$toast?.showSuccess('新增标签成功')
        } catch (error) {
          console.error('新增标签失败:', error)
          window.$toast?.showError('新增标签失败', error.message)
        }
      }
    }

    // 编辑标签相关方法
    const openEditDialog = item => {
      editingItem.value = item
      editTagName.value = item.name
      showEditDialog.value = true
    }

    const closeEditDialog = () => {
      showEditDialog.value = false
      editingItem.value = null
      editTagName.value = ''
    }

    const handleEditTag = async () => {
      if (editTagName.value.trim() && editingItem.value) {
        try {
          await updateDictionaryItem(selectedDimension.value, editingItem.value.id, {
            name: editTagName.value.trim(),
          })
          await loadData() // 重新加载数据
          closeEditDialog()
          window.$toast?.showSuccess('更新标签成功')
        } catch (error) {
          console.error('更新标签失败:', error)
          window.$toast?.showError('更新标签失败', error.message)
        }
      }
    }

    // 删除标签相关方法
    const openDeleteDialog = item => {
      deletingItem.value = item
      showDeleteDialog.value = true
    }

    const closeDeleteDialog = () => {
      showDeleteDialog.value = false
      deletingItem.value = null
    }

    const handleDeleteTag = async () => {
      if (deletingItem.value) {
        try {
          await deleteDictionaryItem(selectedDimension.value, deletingItem.value.id)
          await loadData() // 重新加载数据
          closeDeleteDialog()
          window.$toast?.showSuccess('删除标签成功')
        } catch (error) {
          console.error('删除标签失败:', error)
          window.$toast?.showError('删除标签失败', error.message)
        }
      }
    }

    // 切换状态
    const toggleStatus = async item => {
      try {
        const newStatus =
          item.status === ITEM_STATUS.ACTIVE ? ITEM_STATUS.INACTIVE : ITEM_STATUS.ACTIVE
        await updateDictionaryItem(selectedDimension.value, item.id, {
          status: newStatus,
        })
        await loadData() // 重新加载数据
        window.$toast?.showSuccess('状态更新成功')
      } catch (error) {
        console.error('状态更新失败:', error)
        window.$toast?.showError('状态更新失败', error.message)
      }
    }

    // 组件挂载时加载数据
    onMounted(async () => {
      await loadDictionaryTypes()
      await loadData()
    })

    return {
      selectedDimension,
      searchQuery,
      filteredItems,
      loading,
      showAddTagDialog,
      newTagName,
      showEditDialog,
      editingItem,
      editTagName,
      showDeleteDialog,
      deletingItem,
      dimensionOptions,
      DICTIONARY_TYPES,
      goBack,
      handleImport,
      handleExport,
      closeAddTagDialog,
      handleOverlayClick,
      handleAddTag,
      openEditDialog,
      closeEditDialog,
      handleEditTag,
      openDeleteDialog,
      closeDeleteDialog,
      handleDeleteTag,
      toggleStatus,
      searchData,
    }
  },
}
</script>

<style scoped>
/* 页面容器样式 */
.dictionary-maintenance {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-sizing: border-box;
}

/* 操作栏和筛选栏合并样式 */
.action-filter-bar {
  padding: 12px 16px;
  flex-shrink: 0;
}

.action-filter-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.filter-groups {
  display: flex;
  gap: 16px;
  align-items: center;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 6px;
}

.filter-group label {
  font-size: 13px;
  color: var(--text-secondary);
  white-space: nowrap;
}

.filter-group .input,
.filter-group .select {
  min-width: 120px;
}

.btn-compact {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: white;
  color: var(--text-color);
  cursor: pointer;
  transition: all 0.2s;
  font-size: 13px;
  white-space: nowrap;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.btn-compact:hover {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.btn-compact span {
  font-size: 14px;
}

/* 确保状态按钮的颜色不被覆盖 */
.btn-primary.btn-compact {
  background: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
}

.btn-primary.btn-compact:hover {
  background: #40a9ff;
  border-color: #40a9ff;
  color: white;
}

.table {
  width: 100%;
  border-collapse: collapse;
}

.table th,
.table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

.table th {
  background: #fafafa;
  font-weight: 600;
}

/* 字典表格容器样式 */
.dictionary-table {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
  max-height: calc(100vh - 200px);
}

.dictionary-table .table {
  width: 100%;
  border-collapse: collapse;
  display: block;
  overflow: auto;
  max-height: calc(100vh - 250px);
}

.dictionary-table .table thead {
  position: sticky;
  top: 0;
  z-index: 10;
  background: #fafafa;
  display: table;
  width: 100%;
  table-layout: fixed;
}

.dictionary-table .table tbody {
  display: block;
  overflow-y: auto;
}

.dictionary-table .table tbody tr {
  display: table;
  width: 100%;
  table-layout: fixed;
}

.dictionary-table .table th,
.dictionary-table .table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
  white-space: nowrap;
}

.dictionary-table .table th {
  background: #fafafa;
  font-weight: 600;
}

/* 行号列样式 */
.dictionary-table .table th:first-child,
.dictionary-table .table td:first-child {
  width: 60px;
  text-align: center;
  background-color: #f8f9fa;
  font-weight: 500;
  color: var(--text-secondary);
  border-right: 1px solid var(--border-color);
}

.dictionary-table .table tbody tr:hover td:first-child {
  background-color: #e9ecef;
}

.dictionary-table .table tbody tr:hover {
  background-color: #f5f5f5;
}

.action-buttons {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.action-buttons .btn {
  font-size: 12px;
  padding: 4px 8px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: white;
  color: var(--text-color);
  cursor: pointer;
  transition: all 0.2s;
}

.action-buttons .btn:hover {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.action-buttons .btn.btn-error:hover {
  background: var(--error-color);
  border-color: var(--error-color);
}

.loading-placeholder,
.empty-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  color: var(--text-secondary);
  font-size: 16px;
}

/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  border-radius: var(--border-radius);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  width: 90%;
  max-width: 400px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid var(--border-color);
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-color);
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  color: var(--text-secondary);
  transition: all 0.2s;
}

.close-btn:hover {
  background: #f5f5f5;
  color: var(--text-color);
}

.dialog-body {
  padding: 24px;
  flex: 1;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-color);
}

.form-group .input {
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  font-size: 14px;
  transition: border-color 0.2s;
}

.form-group .input:focus {
  outline: none;
  border-color: var(--primary-color);
}

.warning-text {
  color: #ff4d4f;
  font-size: 14px;
  margin-top: 8px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  border-top: 1px solid var(--border-color);
  background: #fafafa;
}

.btn {
  padding: 8px 16px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.btn-secondary {
  background: white;
  color: var(--text-color);
}

.btn-secondary:hover {
  background: #f5f5f5;
}

.btn-primary {
  background: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #40a9ff;
  border-color: #40a9ff;
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-error {
  background: #ff4d4f;
  border-color: #ff4d4f;
  color: white;
}

.btn-error:hover {
  background: #ff7875;
  border-color: #ff7875;
}

@media (max-width: 768px) {
  .action-filter-row {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .filter-groups {
    flex-direction: column;
    gap: 8px;
  }

  .action-buttons {
    justify-content: center;
  }

  .dialog-content {
    width: 95%;
    margin: 20px;
  }
}
</style>
